//
//  PlaceField.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/1.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
import Foundation
extension XMLReader{

    public class Element:NSObject{
        public var name:String
        public var text:String?
        public var atrributes:[String:String] = [:]
        public var childs:[Element] = []
        public weak var parent:Element? = nil
        
        public init(name:String) {
            self.name = name
            super.init()
        }
        
        public var dict:[String:Any]{
            get{
                var dict:[String:Any] = ["name":self.name]
                if let t = text{dict["text"] = t}
                if(atrributes.count > 0){
                    dict["atrributes"] = atrributes
                }
                var cds:[[String:Any]] = []
                for c in childs {
                    cds.append(c.dict)
                }
                if(childs.count > 0){
                    dict["childs"] = cds
                }
                return dict
            }
        }
        
        public var json:[String:Any]{
            get{
                var dict:[String:Any] = [:]
                if let t = text{dict["text"] = t}
                if(atrributes.count > 0){
                    for (k,v) in atrributes {
                        dict["@\(k)"] = v
                    }
                }
                var childSet:[String:[[String:Any]]] = [:]
                for c in childs {
                    let keys = childSet.keys
                    var list:[[String:Any]] = []
                    if(keys.contains(c.name)){
                        if let ls = childSet[c.name]{
                            list = ls
                        }
                    }
                    list.append(c.json)
                    childSet[c.name] = list
                }
                
                for (k,list) in childSet {
                    if(list.count==1){
                        dict[k] = list[0]
                        
                    }else{
                        dict[k] = list
                    }
                }
                

                return dict
            }
        }
        
        deinit {
        }
    }
}

public typealias JsonResult = (_:[String:Any]?)->Void


public class XMLReader:NSObject,XMLParserDelegate {
    
    var resultBlock:JsonResult? = nil
    
    
    var cache:[Element] = []
    
    var parser_element:Element = Element(name: "root"){
        willSet{
            self.cache.append(parser_element)
        }
    }
    
    
    public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        let e = Element(name: elementName)
        let newParent = parser_element
        e.parent = newParent
        parser_element.childs.append(e)
        e.atrributes = attributeDict
        parser_element = e
        
    }
    
    public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
//        print("end",parser_element,parser_element.parent)
        let e = parser_element
        if let p = e.parent
        {
            parser_element = p
        }
    }
    
    public func parserDidEndDocument(_ parser: XMLParser) {
        let json = parser_element.json
        if (json.keys.count > 0){
            resultBlock?(json)
        }else{
            resultBlock?(nil)
        }
    
//        print("___S",parser_element.json)
    }
    
    
    public var parser:XMLParser? = nil
    public override init() {
        super.init()
    }
    
    public var url:URL? = URL(fileURLWithPath: "/Users/zhuxietong/Desktop/moswift/Sources/moswift/file.xml")
    
    public func parse(url:URL,block:@escaping JsonResult) {
        self.resultBlock = block
        cache = []
        parser_element = Element(name: "root")
        let parser = XMLParser(contentsOf: url)
        parser?.delegate = self
        parser?.parse()
        self.parser = parser
        
    }
    
}
